<script setup>
import { nextTick, onBeforeUnmount, onMounted, reactive, ref } from "vue"
import { OlMap } from "@/utils/openlayers"
import { ElMessage } from "element-plus"
import http from "@/utils/http"
import useEventBus from "@/utils/event.bus"
import { Close } from "@element-plus/icons-vue"
import { useRouter, useRoute } from "vue-router"
import DialogDahuaPlayer from '@/components/DialogDahuaPlayer.vue'
import EventComponents from "@/views/map/components/EventComponents.vue"
import PointInfoComponents from "./PointInfoComponents.vue"
import formatDate from '@/utils/date'
import RealPath from '@/utils/cy.map.realpath'
import {
    fetchSetMaptZoom,
    fetchMapGrid,
    fetchRemoveMarkerById,
    fetchMapMarker,
    fetchMapZones,
    fetchMarkerById
} from '@/api/map.services'
import { editDeviceItem } from "@/api/device.services"
const router = useRouter()
const route = useRoute()
const printFile = () => {
    printJS({
        printable: "map_app", // 标签元素id
        type: "html",
        header: "",
        targetStyles: ["*"],
    })
}

const eventBus = useEventBus()

onMounted(() => {
    if (route.path == "/map") {
        eventBus.on("deviceStatus", deviceStatusinf)
        eventBus.on("eventReal", deviceStatusinfAdd)
        eventBus.on("eventRealUpdate", deviceStatusinfUpdate)
        eventBus.on("eventHandle", deviceStatusinfRemove)
        eventBus.on("guardAlarm", guardAlarmFunc)
        eventBus.on("personPosition", personPositionFunc)
        eventBus.on("alarmTip", deviceStatusinfAdd)
        eventBus.on("access", accessFunc)
        eventBus.on("car", carFunc)
        // eventBus.on("batchHandle", completeMap);
    }
})
onBeforeUnmount(() => {
    if (route.path == "/map") {
        eventBus.off('deviceStatus')
        eventBus.off('eventReal')
        eventBus.off('guardAlarm')
        eventBus.off('eventHandle')
        eventBus.off('personPosition')
        eventBus.off('alarmTip')
        eventBus.off('access')
        eventBus.off('car')
    }
    // 取消订阅所以事件
    // eventBus.all.clear();
})
const carFunc = (msg) => {
    if (!msg.device_id) return
    mapBox.openCarModal(msg)
}
const accessFunc = (msg) => {
    mapBox.openAccessModal(msg)
}
const refDialogDahuaPlayer = ref(null)

const guardAlarmFunc = (e) => {
    mapBox.guardAlarmFunc(e)
}
/**
 * 父组件暴露的方法
 * 用户和父组件数据交互
 * defineEmits
 * 1:
 * 2:点击网格的操作
 * 3:图层移动后更新点位信息
 */
const changeMapEmit = defineEmits([
    "childChangeMap",
    "clickGird",
    "gridModifyEnd1",
    "clickMap",
    "loadingMarkers",
    "addRepairOrder"
])
const deviceStatusinf = (e) => {
    mapBox.setMarkerIcon(e)
    // mapBox.test(alarmPointList.value, e);
}
const deviceStatusinfAdd = (e) => {
    // 防区线点位报警
    if (e.node_id == 4 && e.model_id == 5) {
        addZoneAlarm(e)
        return
    }
    // if (alarmPointList.value[e.device_id]) {

    // } else {

    // }
    const list = JSON.parse(JSON.stringify(alarmPointList.value))
    //新的报警数据
    mapBox.test(list, e)
    if (!alarmPointList.value[String(e.device_id)]) {
        alarmPointList.value[String(e.device_id)] = 1
    } else {
        alarmPointList.value[String(e.device_id)] += 1
    }
    console.log('报警计数', alarmPointList.value)
}

// 报警时间更新数据
const deviceStatusinfUpdate = (e) => {
    // 防区线点位报警
    if (e.node_id == 4 && e.model_id == 5) {
        addZoneAlarm(e)
    }
}

const deviceStatusinfRemove = (e) => {
    // 防区线点位报警
    if (e.node_id == 4 && e.model_id == 5) {
        removeZoneAlarm(e)
        return
    }
    if (!alarmPointList.value[String(e.device_id)]) return
    mapBox.closePopup(e)
    if (alarmPointList.value[String(e.device_id)] == 1) {
        delete alarmPointList.value[String(e.device_id)]
    } else {
        alarmPointList.value[String(e.device_id)] -= 1
    }
    console.log('报警消除', alarmPointList.value)
    // if (e.guard_id) {
    //     //说明是有防区报警
    //     mapBox.closeGuardAlarm(e)
    // }
}
let mapBox = null
const optionsinfo = ref({})
const map_type = ref("")
//地图操作标识
const operate = ref(1)
/**
 * 1:只加载地图
 * 2:加载地图 加载点位
 * 3:加载地图 加载点位 点位编辑
 * 4:加载地图 加载点位 点位详情
 * 5:加载地图 加载网格
 * 5:加载地图 加载网格 网格绘制
 * 6:加载地图 加载网格 网格详情
 * 7:加载地图 加载点位 加载网格
 * 8:加载地图 加载点位 加载网格 点位详情 网格详情
 * 9:记载报警点
 * 10:加载报警网格
 * 13:加载地图 加载指定的数据点位
 * @param {*} options
 * @param {*} type
 */
const gridData = ref({})
const props = defineProps({
    map_id: {
        type: String,
        default: "mapBox"
    }
})
const map_config = ref({})
const init = (options, config, callback, id = 'mapBox') => {
    personPositionData.value = []
    optionsinfo.value = options
    map_type.value = options.map_type
    operate.value = config.type
    gridData.value = options.grid || {}
    map_config.value = config
    mapBox = new OlMap(config.id)
    mapBox.init(options, config, (map, markerC) => {
        completeMap(map, markerC, callback || function () { })
    }, config.id)
}
const polygonOpen = ref(false)
const polygonForm = ref({})
const clickGird = (e) => {
    //点击网格 要区分是 网格编辑还是网格详情
    if (router.currentRoute.value.path == "/map") {
        open.value = false;
        polygonOpen.value = true;
        polygonForm.value = e.values_.data || {};
    } else {
        //如果是防火分区需要给网格添加绘制功能
        // drawPolygon()
        // console.log('e', e.values_.data)
        // drawPolygon([e.values_.data])
    }
    changeMapEmit("clickGird", e);
};
const clickLineFeatures = (e) => {
    deviceForm.value.device_id = e.values_.device_id
    deviceForm.value.device_name = e.values_.device_name
    // deviceForm.value.type = 9999
    open.value = true
    http.get("/v1/marker/guardUnit", { params: { device_id: e.values_.device_id } }).then((res) => {
        if (res.code == 1) {
            deviceForm.value = res.data
        }
    });
}
const gridModifyEnd = (e) => {
    changeMapEmit("gridModifyEnd1", e);
};
const open = ref(false);
const deviceForm = ref({});
const alarmPointList = ref([])

const setstylePolyon1 = (e) => {
    mapBox.setstylePolyon(e);
};
const getalarmPoint = (e) => {
    http.get("/v1/map/alarmPoint", {
        params: { map_id: optionsinfo.value.id },
    }).then((res) => {
        if (res.code == 1) {
            alarmPointList.value = res.data
        }
    })
}
// 点击地图
const clickMap = (e) => {
    changeMapEmit("clickMap", e)
}

const pointInfoRef = ref(null)
/**
 * @description 点击点位
 * * @param {*} e
 * */
const clickFeature = async (e) => {
    // pointInfoRef.value.open(e)
    const result = await fetchMarkerById({ id: e.data_.id })
    if (result.code == 1) {
        deviceForm.value = result.data
        polygonOpen.value = false
        nextTick(() => {
            open.value = true
        })
    }
}
const deleteMarker = async (e, type) => {
    const result = await fetchRemoveMarkerById(e.data_.id)
    if (result.code == 1) {
        ElMessage.success("删除成功")
        mapBox.clearMarkerCenter()
        const zoom = mapBox.map.getView().getZoom()
        optionsinfo.value.zoom = zoom
        changeMapEmit("loadingMarkers", {})
        // completeMap(null,null,{})
        init(optionsinfo.value, map_config.value)
    }
    // this.$emit('getPointInfo', e.data_.marker_id, { map_id: e.data_.uuid }, e.index_)
}
const markers = ref([]);
const markersshow = ref(false)

const removeLine = () => {
    mapBox.removeLine();
}

/**
 * 安全资源运维添加工单
 */
const addRepairOrder = (e) => {
    changeMapEmit("addRepairOrder", e)
}
/**
 * 1:只加载地图
 * 2:加载地图 加载点位
 * 3:加载地图 加载点位 点位编辑
 * 4:加载地图 加载点位 点位详情
 * 5:加载地图 加载网格
 * 5:加载地图 加载网格 网格绘制
 * 6:加载地图 加载网格 网格详情
 * 7:加载地图 加载点位 加载网格
 * 8:加载地图 加载点位 加载网格 点位详情 网格详情
 * @param {*} options
 * @param {*} type
 */
const completeMap = async (map, config, callback) => {
    mapBox.deviceAlarmNum = {}
    alarmPointList.value = {}
    switch (operate.value) {
        case 1:
            // 只加载地图并且点击地图编辑地图类型等
            mapBox.clickMap = clickMap
            break;
        case 2:
            //加载地图 加载点位
            var result = await fetchMapMarker(optionsinfo.value.id, 0)
            if (result.code == 1) {
                markers.value = result.data.data
                markersshow.value = true
                mapBox.createClusterMarker(result.data.data)
            }
            break
        case 3:
            //加载地图 加载点位 点位编辑
            var result = await fetchMapMarker(optionsinfo.value.id, optionsinfo.value.markerType)
            if (result.code == 1) {
                markers.value = result.data.data
                markersshow.value = true
                mapBox.createClusterMarker(result.data.data)
                mapBox.editMarkers(modifyMarkerEnd)
            }

            //清除地图防区图层
            // mapBox.removeLine()
            var res = await fetchMapZones(optionsinfo.value.id)
            if (res.code == 1) {
                mapBox.initDrawZones(res.data, 1)
            }
            var menu = {
                id: map_config.value.id,
                point: [
                    {
                        id: 1,
                        text: "删除点位",
                        callback: deleteMarker,
                    }
                ],
                line: [
                    {
                        id: 1,
                        text: "删除防区",
                        callback: deleteMarker
                    },
                    // {
                    //     id: 2,
                    //     text: "编辑防区",
                    //     callback: editLine
                    // }
                ]
            }
            mapBox.initContentMenu(menu)
            break
        case 4:
            // 加载地图 加载点位 点位详情
            var result = await fetchMapMarker(optionsinfo.value.id, 0)
            if (result.code == 1) {
                markers.value = result.data.data
                markersshow.value = true
                mapBox.createClusterMarker(result.data.data)
                mapBox.clickMarker = clickFeature
            }
            break
        case 5:
            var result = await fetchMapGrid(optionsinfo.value.id)
            if (result.code == 1) {
                mapBox.createPolygon(result.data)
                var menu = {
                    id: map_config.value.id,
                    polygon: [
                        {
                            id: 1,
                            text: "删除生产区域",
                            callback: deleteMarker
                        }
                    ]
                }
                mapBox.initContentMenu(menu)
            }
            break
        case 6:
            //加载地图 加载网格 网格详情
            http.get("/v1/map/grid", {
                params: { map_id: optionsinfo.value.id },
            }).then((res) => {
                if (res.code == 1) {
                    res.data.forEach((item) => {
                        if (item.extend && item.extend.length > 0) {
                            mapBox.createPolygon(item);
                        }
                    })
                }
            })

            break
        case 7:
            //加载地图 加载点位 加载网格
            http.get("/v1/marker/basic", {
                params: { map_id: optionsinfo.value.id },
            }).then((res) => {
                if (res.code == 1) {
                    markers.value = res.data.data;
                    markersshow.value = true;
                    mapBox.createClusterMarker(res.data.data);
                }
            });
            http.get("/v1/map/grid", {
                params: { map_id: optionsinfo.value.id },
            }).then((res) => {
                if (res.code == 1) {
                    res.data.forEach((item) => {
                        if (item.extend && item.extend.length > 0) {
                            mapBox.createPolygon(item);
                        }
                    });
                }
            });
            break;
        case 8:
            open.value = false;
            polygonOpen.value = false
            //加载地图 加载点位 加载网格 点位详情 网格详情
            http.get("/v1/marker/basic", {
                params: { map_id: optionsinfo.value.id, type: 0 },
            }).then((res) => {
                if (res.code == 1) {
                    markers.value = res.data.data;
                    markersshow.value = true;
                    mapBox.createClusterMarker(res.data.data);
                    mapBox.createCircleLayerList(res.data.data);
                    mapBox.clickMarker = clickFeature
                }
            })
            http.get("/v1/map/grid", {
                params: { map_id: optionsinfo.value.id },
            }).then((res) => {
                if (res.code == 1) {
                    res.data.forEach((item) => {
                        if (item.extend && item.extend.length > 0) {
                            mapBox.createPolygon(item);
                        }
                    });
                }
            });
            mapBox.clickGird = clickGird
            break;
        case 9:
            // mapBox.createPolygon(gridData.value.extend, gridData.value)
            if (gridData.value.extend && gridData.value.extend.length > 0) {
                mapBox.createPolygon(gridData.value);
            }
            //加载地图 加载点位
            mapBox.clickGird = clickGird;
            mapBox.gridModifyEnd = gridModifyEnd;
            break;
        case 10:
            // 根据单个设备查找地图 （点位）
            let markerArr = [];
            open.value = false;
            polygonOpen.value = false;
            markerArr.push(optionsinfo.value.marker);
            mapBox.createClusterMarker(markerArr);
            mapBox.createCircleLayerList(markerArr);
            mapBox.clickMarker = clickFeature;
            break;
        case 11:
            // 根据单个区域查找地图 （多边形）
            open.value = false;
            polygonOpen.value = false;
            let polygonArr = optionsinfo.value.marker.extend || [];
            mapBox.createPolygon(polygonArr, optionsinfo.value.marker);
            mapBox.clickGird = clickGird;
            break;
        case 12: //地图划线
            open.value = false
            mapBox.clickMarker = clickFeature
            var res = await fetchMapMarker(optionsinfo.value.id, 0)
            if (res.code == 1) {
                markers.value = res.data.data
                markersshow.value = true
                mapBox.createClusterMarker(res.data.data)
            }

            var res = await fetchMapZones(optionsinfo.value.id)
            if (res.code == 1) {
                mapBox.initDrawZones(res.data, 2)
            }

            var res = await fetchMapGrid(optionsinfo.value.id)
            if (res.code == 1) {
                mapBox.createPolygon(res.data)
            }
            callback?.()
            break;
        // 加载单独点位
        case 13:
            const point = optionsinfo.value.marker || {}
            if (Object.keys(point).length === 0) {
                return
            }
            //点位加载
            if (point.x && point.y) {
                markersshow.value = true
                mapBox.createClusterMarker([point])
                // mapBox.map.getView().setZoom(mapBox.map.getView().getMaxZoom())
                if (mapBox.markerLayers[0]) {
                    mapBox.map.getView().animate({
                        center: mapBox.markerLayers[0].feature.getGeometry().getCoordinates(),
                        duration: 0
                    })
                }
            }
            if (point.type == 4 && point.extend) {
                point.extend = JSON.parse(point.extend)
                mapBox.initDrawZones([point], 2)
            }
            break
        case 14://实时事件 报警点查询地图
            const marker = optionsinfo.value.marker
            mapBox.createClusterMarker([marker])
            const feature = mapBox.markerLayers[0].feature
            mapBox.map.getView().animate({
                center: feature.getGeometry().getCoordinates(),
                duration: 500
            })
            break
        case 15://人员轨迹
            const object = optionsinfo.value.object
            mapBox.createClusterMarker(object.marker)
            //开始画轨迹
            if (object.trackData && object.trackData.length > 0) {
                const realPathCls = new RealPath(mapBox)
                realPathCls.init({
                    points: object.trackData
                })
                realPathCls.startMove()
            }
            break
        case 16://点位/详情/添加工单
            //加载地图 加载点位 点位编辑
            var res = await fetchMapMarker(optionsinfo.value.id, optionsinfo.value.markerType)
            if (res.code == 1) {
                markers.value = res.data.data
                markersshow.value = true
                mapBox.createClusterMarker(res.data.data)
                mapBox.clickMarker = clickFeature
                var menu = {
                    id: map_config.value.id,
                    point: [
                        {
                            id: 1,
                            text: "添加维修工单",
                            callback: addRepairOrder,
                        }
                    ]
                }
                mapBox.initContentMenu(menu)
            }
            break
    }
    if (markers.value.length > 0) {
        markers.value.forEach((item) => {
            if (item.alarm && item.alarm > 0) {
                alarmPointList.value[String(item.device_id)] = item.alarm
            }
        })
    }
    // drawPolygon()
}

// 创建框选工具
const createSelectionTool = (callback) => {
    mapBox.createSelectionTool(callback)
}
// 移除框选工具
const removeSelectionTool = () => {
    mapBox.removeSelectionTool()
}

// 清空框选的矩形选框
const clearSelectionTool = () => {
    mapBox.clearSelectionTool()
}

function getcreateMarkers1(obj) {
    let center = mapBox.getMapCenter();
    var x =
        center[0] +
        Math.round(Math.random() * 100 + 100) +
        parseFloat(getRandomSixNum() / 1000000);
    var y =
        center[1] +
        Math.round(Math.random() * 100 + 100) +
        parseFloat(getRandomSixNum() / 1000000);

    if (obj.x == "" || obj.y == "") {
        obj.x = x;
        obj.y = y;
    }
    mapBox.createMarkers1(obj);
    mapBox.editMarkers(modifyMarkerEnd, removeStare);
}

/**
 * 根据关键字显示 feature
 * @param {String} keyword 关键字
 * @param {String} key 数据的 key 值
 */
function searchFeature(keyword, key = 'name') {
    keyword = keyword.trim()
    const reg = new RegExp(keyword, 'i')

    const result = []

    if (keyword) {
        mapBox.markerLayers.forEach((item, index) => {
            if (reg.test(item.data[key])) {
                result.push(item)
            }
        })
    }

    return result
}

/**
 * 获取坐标内的 featrue
 * @param {Array} coordinates 四角坐标的二位数据 从左上到坐下顺时针获取
 */
function getFeatureInRectangle(coordinates = []) {
    const [lt, rt, rb, lb] = coordinates

    // 计算矩形的左右边界
    const left = Math.min(lt[0], lb[0])
    const right = Math.max(rt[0], rb[0])
    const top = Math.max(lt[1], rt[1])
    const bottom = Math.min(lb[1], rb[1])

    //隐藏掉所有的防区线段
    Object.keys(mapBox.lineLayers).forEach(key => {
        const layer = mapBox.lineLayers[key]
        mapBox.map.removeLayer(layer)
    })

    //处理点位的隐藏
    mapBox.markerLayers.forEach((item, index) => {
        if (item.data.x < left || item.data.x > right || item.data.y < bottom || item.data.y > top) {
            item.feature.setVisibleClose(item.feature)
        } else {
            item.feature.setVisibleOpen(item.feature, item.data)
        }
    })
    // return mapBox.markerLayers.reduce((list, item) => {
    //     if (item.data.x >= left && item.data.x <= right && item.data.y >= bottom && item.data.y <= top) {
    //         list.push(item)
    //     }

    //     return list
    // }, [])
}

/**
 * 根据类型和关键字，筛选需要显示的节点
 * @param {Number[]} types   显示的类型 [1:视频监控,2:公共广播,3:辅助灯光,4:围界防区,5:围界光纤,6:其他设备]
 * @param {String}   keyword 搜索的关键字
 * @param {Function} reset 没有 keyword 时，重置显示的函数
 * @param {Boolean}  visible 根据 keyword 搜索时，是否显示节点
 */
function filterFeature({ subsystem, types, keyword = '', visible = true, visibleAlarm = true }) {
    let featureMap = {}
    for (let key in subsystem) {
        featureMap[key] = []
    }
    let alarmList = []
    let _alarmPointList = {}

    const markerArr = []
    const lineArr = []
    let gridShow = false
    const result = []

    keyword = keyword.trim()

    const reg = keyword ? new RegExp(keyword) : null
    types.forEach(type => {
        markerArr.push(type)
        if (type == 1) {
            lineArr.push(type)
        }
        if (type == 1000) {
            gridShow = true
        }
    })
    if (mapBox.sectorLayers) {
        Object.keys(mapBox.sectorLayers).forEach(key => {
            const layer = mapBox.sectorLayers[key]
            if (types.includes(9)) {
                if (!layer.getVisible()) {
                    layer.setVisible(true)
                }
            } else {
                if (layer.getVisible()) {
                    layer.setVisible(false)
                }
            }
        })
    }
    mapBox.markerLayers.forEach((item, index) => {
        if (!reg) {
            item.feature.setVisibleClose(item.feature)
        }
        item.data.type = 'point'
        if (visibleAlarm && item.data.alarm > 0) {
            _alarmPointList[item.data.device_id] = item.data['alarm']
            alarmList.push(item)
            return
        }

        if (!markerArr.length) {
            return
        }
        if (featureMap[item.data.subsystem_id]) {
            featureMap[item.data.subsystem_id].push(item)
        }
    })
    //搜索防区
    if (lineArr.length) {
        for (let key in mapBox.lineLayers) {
            let lineLayer = mapBox.lineLayers[key]
            const item = {
                layer: lineLayer,
                data: { name: lineLayer.values_.name, id: lineLayer.values_.device_id, type: 'line' }
            }
            if (featureMap[1]) {
                featureMap[1].push(item)
            }
        }
    }

    for (let key in mapBox.Polygonadd) {
        let polygonLayer = mapBox.Polygonadd[key]
        polygonLayer.setVisible(gridShow)
        if (gridShow) {
            const item = {
                layer: polygonLayer,
                data: { name: polygonLayer.values_.name, id: polygonLayer.values_.id, type: 'grid' }
            }
            featureMap[1000].push(item)
        }
    }
    markerArr.forEach(type => {
        featureMap[type]?.forEach(item => {
            if (reg) {
                if (reg.test(item.data.name)) {
                    result.push(item)
                }
                return
            }
            if (!item.data.type || item.data.type == 'point') {
                item.feature.setVisibleOpen(item.feature, item.data)
            }
        })
    })
    if (reg) {
        return result
    }

    alarmList.forEach(item => {
        item.feature.setVisibleOpen(item.feature, item.data)
    })
    setTimeout(() => {
        mapBox.test(_alarmPointList)
    }, 1000)

    featureMap = null

    // 对于线的处理，只能先干掉再通过是否需要显示处理
    Object.keys(mapBox.lineLayers).forEach(key => {
        const layer = mapBox.lineLayers[key]
        mapBox.map.removeLayer(layer)
        !!lineArr.length && mapBox.map.addLayer(layer)
    })
}

function resetKeywordFeature(id, visibleAlarm) {
    let _alarmPointList = {}

    mapBox.markerLayers.forEach((item, index) => {
        item.feature.setVisibleClose(item.feature)

        if (visibleAlarm && item.data.alarm > 0 || item.data.id == id) {
            if (visibleAlarm && item.data.alarm > 0) {
                _alarmPointList[item.data.device_id] = item.data['alarm']
            }
            item.feature.setVisibleOpen(item.feature, item.data)
        }
    })

    setTimeout(() => {
        mapBox.test(_alarmPointList)
    }, 1000)
}
/**
 * @description 移动到指定点位
 * @param {Object} feature
 * @param {Object} featureItem
 * @param {Boolean} visibleAlarm
 * */
function moveToFeature(feature, featureItem, visibleAlarm) {
    let center = []
    switch (featureItem.data.type) {
        case 'line':
            center = feature.values_.middleCoordinate
            Object.keys(mapBox.lineLayers).forEach(key => {
                const layer = mapBox.lineLayers[key]
                mapBox.map.removeLayer(layer)
                if (featureItem.data.id == key * 1) {
                    mapBox.map.addLayer(layer)
                }
            })
            break
        case 'grid':
            center = feature.values_.center
            mapBox.Polygonadd.forEach((item, index) => {
                if (feature.values_.id * 1 == item.values_.id * 1) {
                    item.setVisible(true)
                } else {
                    item.setVisible(false)
                }
            })
            break
        default:
            resetKeywordFeature(featureItem.data.id, visibleAlarm)
            center = feature.getGeometry().getCoordinates()
            break
    }
    // resetKeywordFeature(featureItem.data.id, visibleAlarm)
    // // mapBox.map.getView().setZoom(mapBox.map.getView().getMaxZoom())
    // console.log(feature.getGeometry().getCoordinates())
    mapBox.map.getView().animate({
        center: center,
        duration: 500,
    })
}
/**
 * @description: 通过设备Id移动到目标 feature
 * */
function moveToFeatureById(data) {
    const layer = mapBox.markerLayers.find((item) => item.data.id == data.id)
    const center = layer.feature.getGeometry().getCoordinates()
    mapBox.map.getView().animate({
        center: center,
        duration: 500,
    })
}
function screenFeature(markerArr, polygonArr) {
    let marker_arr = markerArr;
    let polygon_arr = polygonArr;
    if (marker_arr.length > 0) {
        mapBox.markerLayers.forEach((item) => {
            item.feature.setVisibleClose(item.feature);
            marker_arr.forEach((it) => {
                if (
                    it == 7 &&
                    item.data.type == 3 &&
                    item.is_open == 1 &&
                    item.extend
                ) {
                } else if (it == 1 || it == 2 || it == 3 || it == 4) {
                    if (item.data.type == it) {
                        item.feature.setVisibleOpen(item.feature, item.data);
                    }
                }
            });
        });
        if (marker_arr.indexOf(7) == -1) {
            mapBox.circleArr?.forEach((item) => {
                item.setVisible(false);
            });
        } else {
            mapBox.circleArr?.forEach((item) => {
                item.setVisible(true);
            });
        }
    }

    if (polygon_arr.length > 0) {
        mapBox.Polygonadd.forEach((item) => {
            // mapBox.removePolygonByType()
            if (item.getVisible()) {
                item.setVisible(false)
            }
            polygon_arr.forEach((it) => {
                if (item.values_.data.type == it) {
                    // mapBox.addPolygonByType(item)
                    item.setVisible(true)
                }
            });
        });
    }
}

function getcircleLayer1(obj, show) {
    mapBox.createcircleLayer1(obj, show);
}

function getcircleLayer2(obj, show) {
    mapBox.createcircleLayer2(obj, show);
}

const remcontetnList = () => {
    mapBox.contetnList = []
}

function getcontetnList() {
    return mapBox.contetnList
}

function clearFeature1(item) {
    mapBox.clearFeature(item)
}

const removecreatePolygon = (item) => {
    mapBox.removePolygon(item.extend);
}

const removeMap = () => {
    mapBox.removeMap()
}

/** * 添加点位 */
const getRandomSixNum = () => {
    let RandomSixStr = "";
    for (let i = 0; i < 6; i++) {
        if (i == 0) {
            RandomSixStr += String(Math.floor(Math.random() * 5));
        } else {
            RandomSixStr += String(Math.floor(Math.random() * 10));
        }
    }
    return RandomSixStr;
}

function setcontetnList() {
    return markersetcont.value
}

const markersetcont = ref([])
// modifyMarkerEnd 编辑点位方法
const modifyMarkerEnd = (e, position) => {
    let data = e.features.array_[0].values_.data
    markersetcont.value = position;
    if (data.is_open == 1 && mapBox.Layer) {
        mapBox.Layer.getSource()
            .getFeatures()[0]
            .getGeometry()
            .setCenter(position)
        mapBox.Layer.setVisible(true)
    }

    http.post("/v1/marker/create", {
        type: data.type,
        name: data.name,
        device_id: data.device_id,
        map_id: data.map_id,
        x: position[0],
        y: position[1],
        id: data.id,
        range: data.range,
    }).then((res) => {
        if (res.code == 1) {
            setcontetnList()
            ElMessage.success("更新成功")
        }
    })
}
const removeStare = (e, position) => {
    let data = e.features.array_[0].values_.data;
    markersetcont.value = position;
    if (data.is_open == 1) {
        mapBox.Layer.setVisible(false);
    }
}
const editLine = (data) => {
    console.log('开始编辑防区', data)
    //隐藏其他所有点位
    let arr = []
    const polygonMarkerType = [
        { name: "视频监控", switchValue: false, type: 1 },
        { name: "公共广播", switchValue: false, type: 2 },
        { name: "辅助灯光", switchValue: false, type: 3 },
        { name: "围界防区", switchValue: false, type: 4 },
        { name: "围界光纤", switchValue: false, type: 5 },
        { name: "其他设备", switchValue: false, type: 6 }
    ]
    polygonMarkerType.forEach((item) => {
        if (item.switchValue == true) {
            arr.push(item.type)
        }
    })
    filterFeature({ types: arr, visibleAlarm: false })
    //关闭
}
/**
 * 添加点位点击绘制防区
 * 1.需要清除地图上的点位
 * 2.向地图添加启用Draw控件
 */
const drawZones = (data) => {
    mapBox.drawZonesEnd = drawZonesEnd
    mapBox.initDraw(data)
}
/**
 * 防区绘制结束
 */
const drawZonesEnd = (e) => {
    const data = e.data
    http.post("/v1/marker/create", {
        type: data.node_id,
        name: data.device_name,
        device_id: data.id,
        map_id: optionsinfo.value.id,
        extend: e.coordinates
    }).then((res) => {
        ElMessage.success("防区绘制成功")
        mapBox.clearMarkerCenter()
        // init(optionsinfo.value, 3)
        completeMap(null, null, function () { })
        changeMapEmit("loadingMarkers", {})
    })
}
/**
 * @description: 添加点位点击绘制围界
 * @param {*} data
 * @param {*} type
 * @return {*}
 * */
const appendMarker = (data, type) => {
    let center = mapBox.getMarkerCenter()
    //   if (this.map_Type == 'XYZ' || this.map_Type == 'TMap') {
    //     var x = center[0] + parseFloat(this.getRandomSixNum() / 1000000)
    //     var y = center[1] + parseFloat(this.getRandomSixNum() / 1000000)
    //   } else {
    //   }

    var x =
        data.x ||
        center[0] +
        Math.round(Math.random() * 100 + 100) +
        parseFloat(getRandomSixNum() / 1000000);
    var y =
        data.y ||
        center[1] +
        Math.round(Math.random() * 100 + 100) +
        parseFloat(getRandomSixNum() / 1000000);

    if (center && center.length > 0) {
        http.post("/v1/marker/create", {
            type: data.node_id,
            name: data.device_name,
            device_id: data.id,
            map_id: optionsinfo.value.id,
            x: center[0],
            y: center[1],
        }).then((res) => {
            ElMessage.success("添加成功")
            mapBox.clearMarkerCenter()
            const zoom = mapBox.map.getView().getZoom()
            optionsinfo.value.zoom = zoom
            // init(optionsinfo.value, type)
            completeMap(null, null, function () { })
            changeMapEmit("loadingMarkers", {})
        })
    }
}
const dialog = ref(false);
const loading = ref(false);
const form = ref({});
const getouid = () => {
    if (Object.keys(mapBox.features).length == 0) {
        return 0;
    } else {
        return mapBox.features.getGeometry().ol_uid;
    }
};
const editMarker = (e) => {
    form.value = e.data_;
    dialog.value = true;
};
const onClick = (e) => {
    http.post("v1/map/addMarker", form.value).then((res) => {
        form.value = {};
        dialog.value = false;
        init(optionsinfo.value);
    });
}
const chatbox = ref(null)
const dragx = (el) => {
    let oDiv = chatbox.value //当前元素
    let disX = el.clientX - oDiv.offsetLeft
    let disY = el.clientY - oDiv.offsetTop
    document.onmousemove = function (e) {
        //通过事件委托，计算移动的距离
        let l = e.clientX - disX
        let t = e.clientY - disY
        if (l < 0) {
            //如果左侧的距离小于0，就让距离等于0.不能超出屏幕左侧。如果需要磁性吸附，把0改为100或者想要的数字即可
            l = 0
        } else if (
            l >
            document.documentElement.clientWidth - oDiv.offsetWidth
        ) {
            //如果左侧的距离>屏幕的宽度-元素的宽度。也就是说元素的右侧超出屏幕的右侧，就让元素的右侧在屏幕的右侧上
            l = document.documentElement.clientWidth - oDiv.offsetWidth
        }
        if (t < 0) {
            //和左右距离同理
            t = 0
        } else if (
            t >
            document.documentElement.clientHeight - oDiv.offsetHeight
        ) {
            t = document.documentElement.clientHeight - oDiv.offsetHeight
        }
        //移动当前元素
        oDiv.style.left = l + "px"
        oDiv.style.top = t + "px"
    };
    document.onmouseup = function (e) {
        document.onmousemove = null
        document.onmouseup = null
    }
    // 解决有些时候,在鼠标松开的时候,元素仍然可以拖动;
    document.ondragstart = function (ev) {
        ev.preventDefault()
    }
    document.ondragend = function (ev) {
        ev.preventDefault()
    }
    return false
}
const options = ref([])
const paramsval = ref({})
const cmdvalue = ref("")
const visible = ref(false)
//获取布防状态
const getcommand = () => {
    http.get("/v1/device/command").then((res) => {
        if (res.code == 1) {
            options.value = res.data;
        }
    });
};
const subcmd = (cmd, item) => {
    var arr = [];
    arr = item.cmd.filter((data) => data.cmd == cmd);
    if (arr[0].name == "布防") {
        paramsval.value = {
            node_id: item.node_id,
            ip: item.ip,
            cmd: cmdvalue.value,
            type: 1,
            point_number: item.point_number,
            output_number: item.output_number,
            area_number: item.area_number,
        };
        visible.value = true;
    } else {
        paramsval.value = {
            node_id: item.node_id,
            ip: item.ip,
            cmd: cmd,
            type: cmd,
            point_number: item.point_number,
            output_number: item.output_number,
            area_number: item.area_number,
        }
        getcontrol()
    }
}

const getcontrol = () => {
    http.post("/v1/device/control", paramsval.value).then((res) => {
        cmdvalue.value = ""
        ElMessage({
            type: res.code == 0 ? "error" : "success",
            message: res.msg,
        })
    })
}
const changeHot = () => {
    changeMapEmit("childChangeMap", deviceForm.value);
}

//绘制多边形
function drawPolygon(arr) {
    // 触发绘制事件，绘制结束后，调用end函数结束绘制
    let end = mapBox.addInteraction(
        "Polygon",
        arr,
        (bool) => {
            if (bool) {
                xLine.display = "block";
                yLine.display = "block";
            } else {
                xLine.display = "none";
                yLine.display = "none";
            }
        },
        (pixel) => {
            xLine.top = pixel[1] + "px";
            yLine.left = pixel[0] + "px";
        }
    );
}

//横线
const xLine = reactive({
    display: "none",
    width: "100%",
    height: "1px",
    backgroundColor: "blue",
    position: "absolute",
    left: "0px",
    top: "0px",
    zIndex: 99999,
});
//竖线
const yLine = reactive({
    display: "none",
    height: "100%",
    width: "1px",
    backgroundColor: "blue",
    position: "absolute",
    left: "0px",
    top: "0px",
    zIndex: 99999,
});

const openVideo = (data, type = 'real') => {
    http.get('/v1/device/seeVideo', { params: { device_id: data.device_id } }).then(res => {
        if (res.code == 1) {
            if (res.data.length == 0) {
                ElMessage.warning('该设备没有关联视频')
                return
            }
            console.log('开始i打开视频', data)
            //打开摄像机的逻辑
            refDialogDahuaPlayer.value.open({
                type, // [real: 实时预览, record: 录像回放],
                channels: res.data.map(item => {
                    return {
                        channelCode: item.camera_uniq_code,
                        channelName: item.camera_name
                    }
                }),
                title: data.device_name || data.name,
                startTime: new Date(formatDate(new Date, 'YYYY/MM/DD 00:00:00')),
                endTime: new Date()
            }, res.data)
        }
    })
};

const command = (cmd) => {
    http.post('/v1/device/control', {
        device_id: deviceForm.value.device_id,
        cmd: cmd
    }).then(res => {
        if (res.code == 1) {
            ElMessage.success('发送成功')
            http.get("/v1/marker/infoById", {
                params: { id: deviceForm.value.id }
            }).then((res) => {
                if (res.code == 1) {
                    deviceForm.value = res.data
                }
            });
        }
    })
}
const eventComponentsRef = ref(null)
const seeEvent = (id) => {
    nextTick(() => {
        eventComponentsRef.value.eventBoxShow = true
        eventComponentsRef.value.initGuardEventData(id)
    })
}
const openEventBox = () => {
    nextTick(() => {
        eventComponentsRef.value.eventBoxShow = true
        eventComponentsRef.value.initEventAll()
    })
}

const broadcastPopover = ref(false)
const screenMarkerType = ref([
    { name: "播放音频", type: 'audioFiles' },
    { name: "TTS 播报", type: 'tts' },
    { name: "人工广播", type: 'artificial' },
    { name: "批量停止广播任务", type: 'cancelTask' }
])
import DialogPlayAudioFile from '@/components/DialogPlayAudioFile.vue'
import DialogPlayAudioTTS from '@/components/DialogPlayAudioTTS.vue'
import DialogPlayAudioArtificial from '@/components/DialogPlayAudioArtificial.vue'
import DialogCancelAudioTask from '@/components/DialogCancelAudioTask.vue'
const refDialogPlayAudioFile = ref(null)
const refDialogPlayAudioTTS = ref(null)
const refDialogPlayAudioArtificial = ref(null)
const refDialogCancelAudioTask = ref(null)
const handleBroadcastCommand = (type) => {
    broadcastPopover.value = false
    switch (type) {
        // 播放音频文件
        case 'audioFiles':
            // http.get('/v1/broadcast/terminalByDevice', {
            //     params: { device_id: deviceForm.value.device_id }
            // }).then(res => {
            //     if (res.code == 1 && res.data) {
            //         refDialogPlayAudioFile.value.open({ endpointId: res.data })
            //     }
            // })
            refDialogPlayAudioFile.value.open(
                {
                    device_id: deviceForm.value.device_id,
                    node_id: deviceForm.value.node_id
                }
            )
            break
        // TTS播报
        case 'tts':
            // http.get('/v1/broadcast/terminalByDevice', {
            //     params: { device_id: deviceForm.value.device_id }
            // }).then(res => {
            //     if (res.code == 1 && res.data) {
            //         refDialogPlayAudioTTS.value.open()
            //         refDialogPlayAudioTTS.value.terminalID = [res.data]
            //     }
            // })
            refDialogPlayAudioTTS.value.open(
                {
                    device_id: deviceForm.value.device_id,
                    node_id: deviceForm.value.node_id
                }
            )
            break
        // 人工播报
        case 'artificial':
            // http.get('/v1/broadcast/terminalByDevice', {
            //     params: { device_id: deviceForm.value.device_id }
            // }).then(res => {
            //     if (res.code == 1 && res.data) {
            //         refDialogPlayAudioArtificial.value.open()
            //         refDialogPlayAudioArtificial.value.terminalID = [res.data]
            //     }
            // })
            refDialogPlayAudioArtificial.value.open(
                {
                    device_id: deviceForm.value.device_id,
                    node_id: deviceForm.value.node_id
                }
            )
            break
        // 批量停止播放任务
        case 'cancelTask':
            refDialogCancelAudioTask.value.open()
            break
        default:
            break
    }
}

/**
 * 防区标记报警点
 * @param data 
 * @param data.event_id 事件ID 
 * @param data.device_id 设备ID
 * @param data.meters 报警米数
 */
const addZoneAlarm = (data) => {
    mapBox?.addZoneAlarm(data)
}

/**
 * 移除防区标记报警点
 * @param data 
 * @param data.event_id 事件ID 
 * @param data.device_id 设备ID
 */
const removeZoneAlarm = (data) => {
    mapBox?.removeZoneAlarm(data)
}

const setMapZoom = async (command) => {
    let params = {
        id: optionsinfo.value.id
    }
    const zoom = Number(mapBox.map.getView().getZoom().toFixed(2))
    switch (command) {
        case 'default':
            if (zoom == optionsinfo.value.zoom) {
                ElMessage.warning('当前默认缩放层级和当前缩放层级一致，无需设置')
                return
            }
            params.zoom = zoom
            break
        case 'max':
            if (zoom == optionsinfo.value.max_zoom) {
                ElMessage.warning('当前最大缩放层级和当前缩放层级一致，无需设置')
                return
            }
            params.max_zoom = zoom
            break
        case 'min':
            if (zoom == optionsinfo.value.min_zoom) {
                ElMessage.warning('当前最小缩放层级和当前缩放层级一致，无需设置')
                return
            }
            params.min_zoom = zoom
            break
    }
    const result = await fetchSetMaptZoom(params)
    if (result.code == 1) {
        optionsinfo.value.zoom = zoom
        const config = {
            id: 'map_manage',
            type: 3,
            eye_open: false
        }
        init(optionsinfo.value, config)
        ElMessage.success('设置成功')
    }
}
const updateDeviceInfo = async () => {
    const params = {
        id: deviceForm.value.device_id,
        coding: deviceForm.value.coding,
        dvc_installation: deviceForm.value.dvc_installation,
        install_date: deviceForm.value.install_date,
        factory: deviceForm.value.factory,
        contact: deviceForm.value.contact,
        warranty: deviceForm.value.warranty
    }
    const result = await editDeviceItem(params)
    if (result.code == 1) {
        ElMessage.success('更新设备信息成功')
    }
}
/**
 * 人员定位画基础点
 * 轨迹查询
 */
const initTrackMarker = async (data) => {
    mapBox?.initTrackMarker(data)
    let result = []
    data.forEach(item => {
        result.push({
            x: item.x,
            y: item.y
        })
    })
    const realPathCls = new RealPath(mapBox)
    realPathCls.init({
        points: result
    })
    realPathCls.startMove()
}
/**
 * 人员定位实时推送
 * 地图应用展示实时位置
 */
const personPositionData = ref([])
const personPositionFunc = (msg) => {
    if (!mapBox) {
        return
    }
    if (personPositionData.value.includes(msg.person_id)) {
        //如果地图上有该人员，则更新位置
        console.log('更新位置', msg)
        mapBox?.updatePositionLayer(msg)
    } else {
        //新只能基础点位
        personPositionData.value.push(msg.person_id)
        mapBox?.addPositionLayer(msg)
    }
}

/**
 * 加载指定网格
 * 加载指定点
 */
const initAppointGrid = (grid, marker) => {
    mapBox?.createPolygon(grid)
    mapBox?.addPositionLayer(marker)
}

/**
 * @description 地图复位
 * @param {*} options
 */
const mapReset = () => {
    mapBox.map.getView().setZoom(optionsinfo.value.zoom)
    const center = mapBox.getMapCoordinates(optionsinfo.value)
    mapBox.map.getView().animate({
        center: center,
        duration: 500
    })
}
/**
 * @description 设置点位名称显示隐藏
 * @param {*} options
 */
const setFeatureName = (is_open) => {
    if (is_open) {
        mapBox.markerLayers.forEach(item => {
            item.feature.setNameOpen(item.feature)
        })
        Object.keys(mapBox.lineLayers).forEach(key => {
            const layer = mapBox.lineLayers[key]
            layer.setNameOpen(layer)
        })
    } else {
        mapBox.markerLayers.forEach(item => {
            item.feature.setNameClose(item.feature)
        })
        Object.keys(mapBox.lineLayers).forEach(key => {
            const layer = mapBox.lineLayers[key]
            layer.setNameClose(layer)
        })
    }
}


/**
 * @description 截图
 * @param {*} options
 * */
const screenshotEnd = (coordinates) => {
    setTimeout(() => {
        try {
            const ltPixel = mapBox.map.getPixelFromCoordinate(coordinates[0])
            const rtPixel = mapBox.map.getPixelFromCoordinate(coordinates[1])
            const lbPixel = mapBox.map.getPixelFromCoordinate(coordinates[3])
            let sx = Math.round(ltPixel[0])
            let sy = Math.round(ltPixel[1])
            let sw = Math.round(rtPixel[0] - ltPixel[0])
            let sh = Math.round(lbPixel[1] - ltPixel[1])

            // 处理负数情况
            if (sw < 0) {
                sx = sx + sw
                sw = Math.abs(sw)
            }
            if (sh < 0) {
                sy = sy + sh
                sh = Math.abs(sh)
            }
            let canvas = document.getElementById('map_app').getElementsByTagName('canvas')[0]
            let ctx = canvas.getContext('2d')
            let imageData = ctx.getImageData(parseInt(sx), parseInt(sy), parseInt(sw), parseInt(sh))
            let newCanvas = document.createElement('canvas')
            newCanvas.width = parseInt(sw)
            newCanvas.height = parseInt(sh)
            let ctxx = newCanvas.getContext('2d')
            ctxx.putImageData(imageData, 0, 0)

            // 先不移除newCanvas，确保toDataURL能正常导出
            const imageDatas = newCanvas.toDataURL('image/png')
            const elink = document.createElement('a')
            elink.download = '地图截图' + new Date().toLocaleString() + '.png'
            elink.style.display = 'none'
            elink.href = imageDatas;
            document.body.appendChild(elink)
            elink.click()
            document.body.removeChild(elink)
            mapBox.removeSelectionTool()
        } catch (error) {
            console.error('截图过程出错:', error)
            ElMessage.error('截图失败，请重试')
            mapBox.removeSelectionTool()
        }
    }, 500)
}
/**
 * @description 鹰眼地图开关
 * */
const setEyeMap = (val) => {
    if (val) {
        mapBox?.map.addControl(mapBox.overviewMapControl)
    } else {
        mapBox?.map.removeControl(mapBox.overviewMapControl)
    }
}
/**
 * @description 摄像机照射区域开关
 * */
const setRange = (val) => {
    if (val) {
        const camera_types = [47, 219]
        markers.value.forEach((item) => {
            if (camera_types.includes(item.node_id)) {
                mapBox?.createSectorLayer(item)
            }
        })
    } else {
        Object.keys(mapBox.sectorLayers).forEach(key => {
            const layer = mapBox.sectorLayers[key]
            if (layer.getVisible()) {
                layer.setVisible(false)
            }
        })
    }
}
// 输出组件的方法，让外部组件可以调用
defineExpose({
    init,
    appendMarker,
    open,
    drawPolygon,
    getcontetnList,
    removecreatePolygon,
    setstylePolyon1,
    getouid,
    remcontetnList,
    getcreateMarkers1,
    getcircleLayer1,
    getcircleLayer2,
    setcontetnList,
    searchFeature,
    filterFeature,
    screenFeature,
    resetKeywordFeature,
    moveToFeature,
    removeMap,
    printFile,
    removeLine,
    openEventBox,
    getFeatureInRectangle,
    createSelectionTool,
    removeSelectionTool,
    clearSelectionTool,
    drawZones,
    addZoneAlarm,
    removeZoneAlarm,
    setMapZoom,
    initTrackMarker,
    initAppointGrid,
    moveToFeatureById,
    mapReset,
    setFeatureName,
    screenshotEnd,
    setEyeMap,
    setRange
})
</script>
<template>
    <div style="position: relative">
        <div class="mapBox" :id="props.map_id"></div>
        <!--普通设备布点的点位信息-->
        <!-- <PointInfoComponents ref="pointInfoRef" /> -->
        <div class="divesbox" v-if="open && deviceForm.type !== 9999" ref="chatbox" @mousedown="dragx($event)">
            <div class="divesbox-title">
                <p class="marker_title">{{ deviceForm.name }}</p>
                <el-icon :size="20" class="el-icon--right" @click=" open = false; deviceForm = {};"
                    style="cursor: pointer">
                    <Close />
                </el-icon>
            </div>
            <el-form label-width="80px" :class="$style['maeker-form-wrapper']">
                <el-row>
                    <el-col :span="12">
                        <el-form-item label="设备类型:">{{ deviceForm.node_name }}</el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="所在区域:">{{ deviceForm.area_name }}</el-form-item>
                    </el-col>
                </el-row>
                <el-row>
                    <el-col :span="12">
                        <el-form-item label="在线状态:">{{ deviceForm.is_online == 1 ? '在线' : '离线' }}</el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="设备状态:">{{ deviceForm.status_name }}</el-form-item>
                    </el-col>
                </el-row>
                <el-form-item label="工程编码:">
                    <el-input v-model="deviceForm.coding" size="small" placeholder="工程编码" clearable />
                </el-form-item>
                <el-form-item label="安装位置:">
                    <el-input v-model="deviceForm.dvc_installation" size="small" placeholder="安装位置" clearable />
                </el-form-item>
                <el-form-item label="安装时间:">
                    <el-date-picker v-model="deviceForm.install_date" size="small" type="datetime"
                        format="YYYY-MM-DD HH:mm:ss" value-format="YYYY-MM-DD HH:mm:ss" placeholder="安装时间"
                        style="width: 80%" clearable />
                </el-form-item>
                <el-form-item label="维护厂家:">
                    <el-input v-model="deviceForm.factory" size="small" placeholder="维护厂家" clearable />
                </el-form-item>
                <el-form-item label="联系方式:">
                    <el-input v-model="deviceForm.contact" size="small" placeholder="联系方式" clearable />
                </el-form-item>
                <el-form-item label="保修周期:">
                    <el-input v-model="deviceForm.warranty" size="small" placeholder="保修周期" clearable />
                </el-form-item>
            </el-form>
            <div class="mt-4 flex justify-between p-4 border-t border-gray-400 border-solid">
                <el-button type="primary" @click="updateDeviceInfo()" size="small">更新设备信息</el-button>
                <el-button type="success" @click="openVideo(deviceForm, 'real')" size="small">查看视频</el-button>
                <el-button type="success" @click="openVideo(deviceForm, 'record')" size="small">录像回放</el-button>
                <el-popover v-if="deviceForm.node_id == 25" placement="bottom-start" :width="270" trigger="click">
                    <template #reference>
                        <el-button type="primary" @click="broadcastPopover = !broadcastPopover"
                            size="small">广播控制</el-button>
                    </template>

                    <div class="popover_header">
                        <p style="font-size: 12px">广播控制</p>
                        <el-icon @click="broadcastPopover = false" style="cursor: pointer">
                            <Close />
                        </el-icon>
                    </div>
                    <div class="screenBox">
                        <div class="lineBox" v-for="item in screenMarkerType" :key="item.id">
                            <span>{{ item.name }}</span>
                            <el-button type="primary" size="small" @click="handleBroadcastCommand(item.type)">
                                操作
                            </el-button>
                        </div>
                    </div>
                </el-popover>

                <!--德江机场 要求 地图应用/资源可视化不显示 设备得控制命令 -->
                <!-- <el-dropdown trigger="click" type="primary" @command="command" size="small" split-button
                    v-if="deviceForm.command?.length > 0">
                    <span>控制命令</span>
                    <template #dropdown>
                        <el-dropdown-menu>
                            <el-dropdown-item v-for="(item, index) in deviceForm.command" :key="index"
                                :command="item.cmd">{{ item.command_name }}</el-dropdown-item>
                        </el-dropdown-menu>
                    </template>
                </el-dropdown> -->
            </div>
        </div>
        <!--防区布点的点位信息-->
        <div class="divesbox" v-if="open && deviceForm.type == 9999">
            <div class="divesbox-title">
                <p class="marker_title">{{ deviceForm.device_name }}</p>
                <el-icon :size="20" class="el-icon--right" @click=" open = false; deviceForm = {};"
                    style="cursor: pointer">
                    <Close />
                </el-icon>
            </div>
            <el-table :data="deviceForm.unit" style="width: 100%" height="300px" size="small">
                <el-table-column prop="unit_name" label="震动单元名称" align="center" />
                <el-table-column prop="meters" label="振动单元米标" align="center" />
            </el-table>
            <div class="mt-4 flex justify-between p-4 border-t border-gray-400 border-solid">
                <el-button type="primary" @click="openVideo(deviceForm)" size="small">查看视频</el-button>
            </div>
        </div>

        <el-dialog title="布防命令" :width="400" v-model="visible" @open="getcommand(); cmdvalue = '';"
            :close-on-click-modal="false" :close-on-press-escape="false">
            <div style="padding: 0 20px; height: 500px; overflow-y: scroll">
                <el-radio-group v-model="cmdvalue" class="ml-4">
                    <el-radio v-for="(its, iti) in options" :key="iti" :label="its.cmd" size="large">
                        {{ its.name }}
                    </el-radio>
                </el-radio-group>
            </div>
            <template #footer>
                <span class="dialog-footer text-center">
                    <el-button @click="visible = false; cmdvalue = '';">取消</el-button>
                    <el-button type="primary"
                        @click="getcontrol(); paramsval.cmd = cmdvalue; visible = false;">确定</el-button>
                </span>
            </template>
        </el-dialog>
        <el-drawer v-model="dialog" title="编辑点位信息" direction="ltr" class="demo-drawer">
            <div class="demo-drawer__content">
                <el-form :model="form">
                    <el-form-item label="设备名称" label-width="150px">
                        <el-input v-model="form.device_name" autocomplete="off" />
                    </el-form-item>
                </el-form>
                <div class="demo-drawer__footer">
                    <el-button @click="dialog = false">取消</el-button>
                    <el-button type="primary" :loading="loading" @click="onClick">
                        {{ loading ? "提交中 ..." : "提交" }}
                    </el-button>
                </div>
            </div>
        </el-drawer>
        <div style="display: none" class="warning sky-marker-shashuo"></div>
        <DialogDahuaPlayer ref="refDialogDahuaPlayer" />
        <!-- <EventComponents ref="eventComponentsRef" /> -->
        <DialogPlayAudioFile ref="refDialogPlayAudioFile" />
        <DialogPlayAudioTTS ref="refDialogPlayAudioTTS" />
        <DialogPlayAudioArtificial ref="refDialogPlayAudioArtificial" />
        <DialogCancelAudioTask ref="refDialogCancelAudioTask" />
    </div>
</template>
<style lang="scss" scoped>
.mapBox {
    width: 100%;
    height: 100%;
    position: relative;
}

.divesboxfoot {
    width: 100%;
    height: 50px;
    background: #10295d;
}

.row-bg {
    width: 100%;
    display: flex;
    line-height: 35px;
    color: rgb(83, 88, 98);

    p {
        font-family: HarmonyOS Sans SC;
        font-size: 14px;
        font-weight: 400;
        letter-spacing: 0px;
        text-align: right;
    }
}

/*:deep(.el-form-item) {
    margin-bottom: 0;
}*/

.sky-marker-shashuo {
    width: 36px;
    height: 36px;
    animation: skyMarkerShashuo 5s infinite;
}

@keyframes skyMarkerShashuo {
    0% {
        box-shadow: 0 0 5px 5px red;
    }

    50% {
        box-shadow: 0 0 5px 5px transparent;
    }

    100% {
        box-shadow: 0 0 5px 5px red;
    }
}

.divesbox {
    width: 500px;
    background-color: #ffff;
    position: absolute;
    right: 100px;
    top: 180px;
    border-radius: 2px;
    box-shadow: var(--el-box-shadow-light);
}

.divesbox-title {
    padding: 0 15px 0 15px;
    display: flex;
    flex-direction: row;
    justify-content: space-between;
    height: 40px;
    align-items: center;
    background: #0562EE;
    color: #fff;
}

.inlineBox {
    font-size: 14px;
    display: flex;
    flex-direction: column;
    box-sizing: border-box;
    padding: 15px;

    .wrapDiv {
        height: 30px;
        line-height: 30px;
        color: #7A7A7A;

    }

    .wrapDiv_text {
        color: #000;
        margin-left: 10px;
    }

    .buttonBox {
        width: 100%;
        height: 20px;
        line-height: 20px;
        display: flex;

        .el-button {
            border-radius: 5px;
        }
    }
}

.marker_title {
    font-size: 15px;
    font-weight: bold;
    font-weight: 700;
}

.popover_header {
    display: flex;
    justify-content: space-between;

    p {
        font-size: 14px;
    }
}

.screenBox {
    display: flex;
    flex-direction: column;
    margin-top: 10px;

    .lineBox {
        display: flex;
        justify-content: space-between;
        height: 32px;
    }
}
</style>
<style lang="scss" module>
.maeker-form-wrapper {
    padding: 10px;

    & [class~='el-form-item'] {
        margin-bottom: 0;
    }

    & [class~='el-input'] {
        width: 80%;
    }
}
</style>
<style lang="scss">
.ol-overviewmap {
    right: unset;
    top: unset;
    left: 0.5em;
    bottom: 0.5em;
    width: 300px;
    height: 200px;

    .ol-overviewmap-map {
        width: 300px;
        height: 200px;
    }
}
</style>